package com.tensquare.search.controller;

import com.tensquare.entity.PageResult;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.search.model.Article;
import com.tensquare.search.service.ArticleSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleSearchController {

    @Autowired
    private ArticleSearchService searchService ;

    private Result result = new Result(true, StatusCode.OK);

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result deleteArticleById(@PathVariable String id){
        Article data = searchService.findArticleById(id);
        searchService.deleteArticleById(id);
        result.setMessage("删除成功");
        result.setData(data);
        return result ;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result updateArticle(@RequestBody Article article, @PathVariable String id){
        searchService.updateArticle(id, article);
        Article data = searchService.findArticleById(id);
        result.setMessage("修改成功");
        result.setData(data);
        return result ;
    }

    @RequestMapping(method = RequestMethod.POST)
    public Result saveArticle(@RequestBody Article article) {
        searchService.saveArticle(article);
        result.setMessage("保存成功");
        result.setData(article);
        return result ;
    }

    @RequestMapping(value = "/{id}")
    public Result findArticleById(@PathVariable String id) {
        Article article = searchService.findArticleById(id);
        result.setMessage("查询成功");
        result.setData(article);
        return result ;
    }

    @RequestMapping()
    public Result findAllArticle() {
        List<Article> articleList = searchService.findAllArticle();
        result.setMessage("全部文章");
        result.setData(articleList);
        return result ;
    }

    @RequestMapping(value = "/findByKey/{key}/{page}/{size}")
    public Result findArticleByKey(@PathVariable String key , @PathVariable Integer page , @PathVariable Integer size ) {
        Page<Article> pageList = searchService.findByKey(key, page, size);
        PageResult<Article> data = new PageResult<Article>(pageList.getTotalElements(), pageList.getContent());
        result.setMessage("分页查询成功");
        result.setData(data);
        return result ;
    }

}
